﻿using System;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
using Foothill.Common;
using Foothill.Common.Logging;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.AdService;
using Foothill.Service.MiscInfo;
using Foothill.Service.Session;
using Foothill.Service.UploadPhoto;
using Foothill.Service.VehicleInfo;
using Foothill.Service.UserAccount;

namespace Foothill.Web
{
    public partial class ForSaleAdDetail : FoothillBasePage
    {
        private IAdService _adService;
        private ISessionService _sessionService;
        private IVehicleInfoService _vehicleInfoService;
        private IMiscInfoService _miscInfoService;
        private IUploadPhotoService _uploadPhotoService;
        private int _PostId;

        public int PostId
        {
            set
            {
                ViewState["PostId"] = value;
            }

            get
            {
                int result = 0;
                object obj = ViewState["PostId"];

                result = (obj == null)? 0 : Convert.ToInt32(obj);

                return result;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            _sessionService = IocContainer.GetInstance<ISessionService>();
            _vehicleInfoService = IocContainer.GetInstance<IVehicleInfoService>();
            _miscInfoService = IocContainer.GetInstance<IMiscInfoService>();
            _adService = IocContainer.GetInstance<IAdService>();
            _uploadPhotoService = IocContainer.GetInstance<IUploadPhotoService>();
            
            if (!IsPostBack)
            {
                DisplayAdDetail();
            }
        }

        // increase the number of times this post is clicked on if applicable 
        private void IncreaseNumOfClickedOn(int postId)
        {
            object obj = Request.QueryString[GlobalQueryString.FromSearchListQsName];

            if (obj != null)
            {
                _adService.IncreaseNumberOfTimeClicked(postId);
            }
        }

        private void DisplayAdDetail()
        {
            // see if the request is redirected from adv search
            object o = Request.QueryString[GlobalQueryString.AdDetailsQsName];

            if (o != null)
            {
                int postId = 0;
                Int32.TryParse(o.ToString(), out postId);

                if (postId > 0)
                {
                    PostId = postId;
                    ForSaleAd post = _adService.GetForSaleAdById(postId);

                    PopulateDisplayControls(post);
                    PopulatePostUserInfo(post);
                    DisplayUploadedPhotos(post);
                    IncreaseNumOfClickedOn(postId);
                }
            }
        }

        private void PopulateDisplayControls(ForSaleAd post)
        {
            if (post == null)
            {
                return;
            }

            lblVehicleType.Text = post.GetVehicleTypeString().ToUpper();

            lblPrice.Text = "$" + post.Price.ToString();

            lblTransmissionValue.Text = post.TransmissionTypeName;
            lblListingTypeValue.Text = post.ListingTypeString;
            lblConditionValue.Text = post.VehicleConditionName;
            lblDatePostedValue.Text = post.TimePosted.ToString("D");
            lblNumClicksValue.Text = post.NumClickedOn.ToString();
            lblNumSavedValue.Text = post.NumSaved.ToString();

            lblDescriptionDetail.Text = post.Description.Replace(Environment.NewLine, "<br>");
        }

        private void PopulatePostUserInfo(ForSaleAd post)
        {
            if (post.PostedByUserAccountId > 0)
            {
                // post by a registered user 
                pnlUnregisteredUser.Visible = false;

                IUserAccountService userAccountService = IocContainer.GetInstance<IUserAccountService>();
                UserAccountDto userDetails = userAccountService.GetUserAccountDetailsByUserId(post.PostedByUserAccountId);

                if (userDetails != null)
                {
                    lblRegisteredContact.Text = userDetails.ContactName;
                    lblRegisteredPhone.Text = post.ContactPhone;
                    lblRegisteredEmail.Text = post.ContactEmail;
                    lblRegisteredCity.Text = post.CityName;

                    if (string.IsNullOrWhiteSpace(userDetails.UserProfilePhotoPath))
                    {
                        imgUserProfile.ImageUrl = GlobalSettings.DefaultProfilePhoto;
                    }
                    else
                    {
                        imgUserProfile.ImageUrl = userAccountService.GetProfilePhotoFileUrl(userDetails.UserProfilePhotoPath);
                    }

                    if (string.IsNullOrWhiteSpace(userDetails.UserLogoFilePath))
                    {
                        imgUserLogo.Visible = false;
                    }
                    else
                    {
                        imgUserLogo.ImageUrl = userAccountService.GetLogoFileUrl(userDetails.UserLogoFilePath);
                    }
                }
            }
            else
            {
                // post by anonymous user
                pnlRegisteredUser.Visible = false;

                lblAnonymousContact.Text = post.ContactName;
                lblAnonymousPhone.Text = post.ContactPhone;
                lblAnonymousEmail.Text = post.ContactEmail;
                lblAnonymousCity.Text = post.CityName;
            }
        }

        private void DisplayUploadedPhotos(ForSaleAd post)
        {
            string profilePhotoPath;

            try
            {
                profilePhotoPath = Path.Combine(GlobalSettings.UploadPhotoFolder, Path.GetFileName(post.ProfilePhotoPath));

                if (File.Exists(Server.MapPath(profilePhotoPath)))
                {
                    imgProfile.ImageUrl = profilePhotoPath;
                    hlkProfilePhoto.NavigateUrl = profilePhotoPath;
                }
                else
                {
                    imgProfile.ImageUrl = GlobalSettings.PhotoNotAvailablePath;
                }
            }
            catch (Exception ex)
            {
                imgProfile.ImageUrl = GlobalSettings.PhotoNotAvailablePath;
                Log.Error(FoothillModule.View, string.Format("Error in Display Uploaded Photo: {0}", ex.Message));
            }

            dltPhotos.DataSource = _uploadPhotoService.GetForSaleAdUploadedPhotos(post.AdId).OrderBy(p => p.DisplayIndex).ToList(); ;
            dltPhotos.DataBind();
        }

        protected void dltPhotos_OnItemCreated(object sender, DataListItemEventArgs e)
        {
            if ( e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem )
            {
                UploadPhoto photo = e.Item.DataItem as UploadPhoto;

                if (photo != null)
                {
                    ImageButton btn = e.Item.FindControl("btnThumbnail") as ImageButton;

                    string thumbnailPath;
                    
                    try
                    {
                        thumbnailPath = Path.Combine(GlobalSettings.ThumbnailFolder, Path.GetFileName(photo.PathOnServer));

                        string absolutePath = Server.MapPath(thumbnailPath);

                        if (!File.Exists(absolutePath))
                        {
                            thumbnailPath = GlobalSettings.PhotoNotAvailablePath;
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        thumbnailPath = GlobalSettings.PhotoNotAvailablePath;
                    }

                    btn.ImageUrl = thumbnailPath;
                }
            }
        }

        // delete the uploaded photo
        protected void btnThumbnail_Click(object sender, EventArgs e)
        {
            DataListItem item = (DataListItem)((ImageButton)sender).NamingContainer;

            // datakey is photopath
            string photoPath = dltPhotos.DataKeys[item.ItemIndex].ToString();

            imgProfile.ImageUrl = string.Format("{0}/{1}", GlobalSettings.UploadPhotoFolder, Path.GetFileName(photoPath));

            dltPhotos.DataSource = _uploadPhotoService.GetForSaleAdUploadedPhotos(PostId);
            dltPhotos.DataBind();
        }
    }
}
